<template>
  <div>
    <table border="1" width="700" style="border-collapse: collapse">
      <caption>购物车</caption>
      <thead>
        <tr>
          <th>
            <input type="checkbox" v-model="checkAll" />
            <span>全选</span>
          </th>
          <th>名称</th>
          <th>价格</th>
          <th>数量</th>
          <th>总价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <hang
          v-for="(item,index) in list"
          :arr="item"
          @returnItem="getItem"
          :key="index"
          @totalPrice="totalPrice1"
          @delet="ondel"
          @ischack="check"
        ></hang>
      </tbody>
      <tfoot>
        <tr>
          <td>合计:</td>
          <td colspan="5">{{total}}</td>
        </tr>
      </tfoot>
    </table>
    <ceshi></ceshi>
  </div>
</template>
<script>
import hang from "./components/tr";
import ceshi from "./components/ceshiti";
export default {
  components: {
    hang,
    ceshi
  },
  data() {
    return {
      list: [
        { id: 1, ischeck: false, name: "诸葛亮", price: 1000, totalprice: 0 },
        { id: 2, ischeck: false, name: "蔡文姬", price: 1500, totalprice: 0 },
        { id: 3, ischeck: false, name: "妲己", price: 2000, totalprice: 0 },
        { id: 4, ischeck: false, name: "鲁班", price: 2200, totalprice: 0 }
      ]
    };
  },
  methods: {
    getItem(v) {
      this.list.forEach((item, index) => {
        if (item.id === v.id) {
          this.list[index] = v;
        }
      });
      console.log(this.list);
    },
    totalPrice1(i, val) {
      this.list.forEach(item => {
        if (item.id == i) {
          item.totalprice = val;
        }
      });
    },
    ondel(v) {
      this.list.forEach((item, i) => {
        if (item.id == v) {
          this.list.splice(i, 1);
        }
      });
    },
    check(id, val) {
      // this.checkList.push(v);
      // console.log(this.checkList);
      console.log(id, val);
      this.list.forEach(item => {
        if (item.id == id) {
          item.ischeck = val;
        }
      });
      console.log(this.list);
    }
  },
  computed: {
    checkAll: {
      set(val) {
        this.list.forEach(item => (item.ischeck = val));
        console.log(val, this.list);
      },
      get() {
        return this.list.every(item => item.ischeck == true);
      }
    },
    total() {
      return this.list.reduce((num, item) => (num += item.totalprice), 0);
    }
  },
  watch: {
    // list: {
    //   handler(newval) {
    //     console.log(newval);
    //     let a = 0;
    //     newval.forEach(item => {
    //       a = a + item.totalprice;
    //     });
    //     // console.log(this.total);
    //   },
    //   deep: true
    // }
  },
  created() {},
  mounted() {}
};
</script>

<style scoped>
</style>